var qs = require("querystring")
var jwt = require('jsonwebtoken');
module.exports=async (resquest,response)=>{
    var url = resquest.url; //path?query#hash
    var path = url.split("?")[0];
    var query =  url.split("?")[1];
    var method = resquest.method;
    if(path === "/api/blog/list" && method === "GET"){
        //获取postman中传来的数据(get)
        var queryObj = qs.parse(query);
        var author = queryObj.author;
        var keyword = queryObj.keyword;
        //访问数据库
        var sql = "select id,title,author from blogs where 1=1 and status=0";
        if(author){sql += `and author ='${author}' `};
        if(keyword){sql += `and title like '%${keyword}%' `};

        console.log(sql)

        var data = "";
        data = await new Promise((reslove,reject)=>{
            global.connection.query(sql, (error, results)=> {
                if (error) {
                    reject(error)
                }else{
                    reslove(results)
                }
            });
        }) 
        return {data:data};
    }
    if(path === "/api/blog/new"  && method === "POST"){
        //1. 获取postname传来的数据(post)
        var body = await new Promise((reslove,reject)=>{
            var body="";
            resquest.on("data",(data)=>{
                body += data.toString()
            })
            resquest.on("end",()=>{
                reslove(body)
            })
        })
        //2. 将前端传来的数据加入到数据库中
        var bodyObj = JSON.parse(body);
        var title = bodyObj.title;
        var content = bodyObj.content;
        var createtime = bodyObj.createtime;
        var author = bodyObj.author;

        var sql = 
        "INSERT INTO blogs (title,content,createtime,author) " +
        `VALUES ("${title}","${content}","${createtime}","${author}")`
        
        var data = "";
        data = await new Promise((reslove,reject)=>{
            global.connection.query(sql, (error, results)=> {
                if (error) {
                    reject(error)
                }else{
                    reslove(results)
                }
            });
        }) 
        return {data:data};
    }
    if(path === "/api/blog/update"  && method === "POST"){
      try{
        //获取postman中传来的id
        var queryObj = qs.parse(query);
        var id = queryObj.id;
        //获取postman中传来的更新数据
        var body = await new Promise((reslove,reject)=>{
          var body="";
          resquest.on("data",(data)=>{
            body += data.toString()
          })   
          resquest.on("end",()=>{
            reslove(body)
          })
        })
        var bodyObj = JSON.parse(body);
        var {title,content,token} = bodyObj;

        //判断访问当前接口时 用户是否登入
        var decoded=jwt.verify(token,"damulovezdy");
        if(decoded,username){
          //处于登入状态
          var sql = `select author from blogs WHERE id=${id} and status=0`;
          //执行SQL
          var data1 =[];
          data1 = await new Promise((reslove,reject)=>{
            global.connection.query(sql, (error, results)=> {  
              if (error) {
                reject(error)
              }else{
                reslove(results)
              }
            });
          }) 
          //判断更新的数据是否存在 
          if(data1.length>0){
            //更新数据存在
            //判断更新数据的作者是否为登入用户
            var author=data1[0].author;
            if(decoded.username==author){

            }else{
              return{
                message:"author is empty",
                data:"error"
              }
            }
          }else{
            //更新的数据不存在
            return{
              message:"data is empty",
              data:"error"
            }
          }
        }
      }catch(error){
          //处于未登入状态
          return{
            message:"token is error",
            data:"error"
          }
        }
        //组装SQL
        var updateSQL = "";
        if(title){updateSQL+=`title = '${title}',`}
        if(content){updateSQL+=`content = '${content}',`}
     
        updateSQL = updateSQL.substring(0,updateSQL.length-1)
        var sql = "UPDATE blogs SET "
                     + updateSQL +` WHERE id=${id};`
        //执行SQL
        var data = "";
        data = await new Promise((reslove,reject)=>{
            global.connection.query(sql, (error, results)=> {
                if (error) {
                    reject(error)
                }else{
                    reslove(results)
                }
            });
        }) 
        return {data:data};
    }
    if(path === "/api/blog/detail" && method === "GET"){
      //获取postman中传来的id
      var queryObj = qs.parse(query);
      var id = queryObj.id;
      //拼sql
      var sql = `select content from blogs WHERE id=${id} and status=0`;
      //执行SQL
      var data = "";
      data = await new Promise((reslove,reject)=>{
          global.connection.query(sql, (error, results)=> {
              if (error) {
                  reject(error)
              }else{
                  reslove(results)
              }
          });
      }) 
      return {data:data};
    }
    if(path === "/api/blog/del"  && method === "GET"){
        //获取postman中传来的id
       try { 
        var queryObj = qs.parse(query);
        var id = queryObj.id;
        var bodyObj = JSON.parse(body);
        var author = bodyObj.author;
        var token =bodyObj.token;
        var decoded = jwt.verify(token, 'damulovezdy');
       if(decoded.username){
          //拼sql
          var sql = `UPDATE FROM blogs WHERE id=${id} and author=${author} and status=0 `;
          //执行SQL
          var data = "";
          data = await new Promise((reslove,reject)=>{
              global.connection.query(sql, (error, results)=> {
                  if (error) {
                      reject(error)
                  }else{
                      reslove(results)
                  }
              });
          }) 
          return {data:data};
       }
       } catch (error) {
                return{
                  data:"error",
                  message:"token is error"
                }
       }
      
    }
}

